package com.apes.crm.vip.masterdata.service;

import com.apes.crm.vip.masterdata.model.AccountType;
import com.apes.crm.vip.masterdata.repository.AccountTypeRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 账户类型
 *
 * @author wuq
 * @create 2018-10-10 15:35
 */
@Service("vipAccountTypeService")
public class AccountTypeService extends DomainService {

    @Autowired
    public AccountTypeRepository accountTypeRepository;

    /**
     * 保存
     * @param request
     * @return
     */
    public AccountType save(SimpleRequest request) {
        AccountType accountType = request.getO(AccountType.class);
        return accountTypeRepository.saveAndFlush(accountType);
    }

    /**
     * 检查数据判断，判读当前的输入版本信息
     * @param request
     */
    public void checkData(SimpleRequest request){
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        AccountType oldAccountType = accountTypeRepository.findOne(id);
        if (oldAccountType == null) throw new RuntimeException("账户类型【" + id + "】在系统中不存在。");
        if (oldAccountType.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
    }


    public AccountType update(SimpleRequest request) {
        // 检查数据
        checkData(request);

        AccountType accountType = request.getO(AccountType.class);
        return accountTypeRepository.saveAndFlush(accountType);
    }

    public String delete(SimpleRequest request) {
        // 检查数据
        checkData(request);
        AccountType accountType = request.getO(AccountType.class);
        accountTypeRepository.delete(accountType);
        return "删除成功！";
    }

}
